/**
 * 广寒宫
 * 网址:www.guanghangong.xyz
 */
package com.moon.admin.flowable.controller;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;
import org.flowable.engine.ProcessEngine;
import org.flowable.engine.repository.Deployment;
import org.flowable.engine.repository.DeploymentQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Maps;
import com.moon.admin.flowable.entity.ActCnDeploymentEntity;
import com.moon.admin.flowable.entity.FlowModelUserEntity;
import com.moon.admin.flowable.service.FlowModelUserService;
import com.moon.admin.framework.secure.annotation.FormRepeat;
import com.moon.admin.framework.secure.annotation.PreAuth;
import com.moon.admin.framework.springmvc.domain.R;
import com.moon.admin.framework.syslog.annotation.SysLog;
import com.moon.admin.framework.util.MoonException;
import com.moon.admin.framework.util.ToolUtils;

/**
 * 流程授权管理
 * @author ninglong
 * @date 2020年1月11日
 * @version 1.0
 */
@RestController
@RequestMapping("/flowable/user")
public class FlowableModelUserController {

	
	@Autowired
	private FlowModelUserService actFlowModelUserService;
	@Autowired
	private ProcessEngine processEngine;
	
	/**
	 * 用户绑定流程
	 */
	@GetMapping("/binding")
	@PreAuth("flowable_user_binding")
	@SysLog(mod = "流程授权管理", fun = "用户流程授权")
	@FormRepeat
	public R<Void> binding(String modelKey,String userIds){
		Deployment deployment = processEngine.getRepositoryService().createDeploymentQuery().deploymentKey(modelKey).latest().singleResult();
		if(null == deployment){
			throw new MoonException("流程绑定失败，流程未部署");
		}
		List<Integer> userIdList = ToolUtils.toIntList(userIds); 
		actFlowModelUserService.binding(modelKey,deployment.getCategory(),userIdList);
		return R.success();
	}
	
	@GetMapping("getUserIdByBindingModel")
	public R<List<Integer>> getUserIdByBindingModel(String modelKey,String category) {
		List<FlowModelUserEntity> checkFlowUsers = actFlowModelUserService.list(Wrappers.<FlowModelUserEntity>lambdaQuery().eq(FlowModelUserEntity::getModelKey, modelKey)
				.eq(FlowModelUserEntity::getFlowTypeId, category));
		return R.success(checkFlowUsers.stream().map(entity->entity.getUserId()).collect(Collectors.toList()));
	}
	
	/**
	 * 分页查询用户以绑定的流程
	 */
	@GetMapping("getSelfModelDeployList")
	public R<List<Integer>> selectModelBindedList(String modelKey,String category) {
		List<FlowModelUserEntity> checkFlowUsers = actFlowModelUserService.list(Wrappers.<FlowModelUserEntity>lambdaQuery().eq(FlowModelUserEntity::getModelKey, modelKey)
				.eq(FlowModelUserEntity::getFlowTypeId, category));
		return R.success(checkFlowUsers.stream().map(entity->entity.getUserId()).collect(Collectors.toList()));
	}
	
	/**
	 * 分页查询用户以绑定的流程
	 */
	@PreAuth("flowable_start_task_view")
	@PostMapping("getSelfModelDeployList")
	public R<IPage<ActCnDeploymentEntity>> selectModelBindedList(@RequestBody ActCnDeploymentEntity actCnDeploymentEntity) {
		IPage<ActCnDeploymentEntity> page = new Page<>(actCnDeploymentEntity.getPage(),actCnDeploymentEntity.getLimit());
		if(StringUtils.isEmpty(actCnDeploymentEntity.getUserId())) {
			return R.fail("请选择要查询的用户");
		}
		List<FlowModelUserEntity> flows = actFlowModelUserService.list(Wrappers.<FlowModelUserEntity>lambdaQuery()
				.eq(FlowModelUserEntity::getUserId, actCnDeploymentEntity.getUserId()));
		if(ToolUtils.isEmpty(flows)){
			return R.success(page);
		}
		List<String> deploymentIds = new ArrayList<String>();
		for(FlowModelUserEntity flowModelUser:flows) {
			deploymentIds.add(flowModelUser.getModelKey()+"_"+flowModelUser.getFlowTypeId());
		}
		DeploymentQuery deploymentQuery = processEngine.getRepositoryService().createDeploymentQuery();
		if(ToolUtils.isNotEmpty(actCnDeploymentEntity.getName())){
			deploymentQuery.deploymentNameLike("%" + actCnDeploymentEntity.getName() + "%");
		}
		List<Deployment> list = deploymentQuery.list();
		//取出相同key_category里部署时间最晚的一条数据
		Map<String,ActCnDeploymentEntity> map = Maps.newHashMap();
		for(Deployment entity:list) {
			ActCnDeploymentEntity tmp = new ActCnDeploymentEntity(entity);
			String key = tmp.getModelKey()+"_"+tmp.getCategory();
			if(!deploymentIds.contains(key))continue;
			ActCnDeploymentEntity maxDeployMent = map.get(key);
			if(maxDeployMent==null || maxDeployMent.getDeployTime().getTime()<tmp.getDeployTime().getTime()) {
				map.put(key, tmp);
			}
		}
		List<ActCnDeploymentEntity> records = new ArrayList<ActCnDeploymentEntity>(map.values());
		page.setTotal(records.size());
		records = records.stream().sorted(Comparator.comparing(ActCnDeploymentEntity::getDeployTime).reversed()).skip(actCnDeploymentEntity.getStart()).limit(actCnDeploymentEntity.getLimit()).collect(Collectors.toList());
		page.setRecords(records);
		return R.success(page);
	}
}